<template>
  <div class="loginView">
    <div class="login">
      <div class="title">登录</div>

      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="rules"
        label-width="80px"
        class="login-form"
      >
        <el-form-item label="账号" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="loginForm.password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-button type="primary" @click="login" class="login-button">登录</el-button>
      </el-form>

      <div class="register-link">没有账号？<router-link to="/register">去注册</router-link></div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores'
import { Api } from '@/api'
import { ElMessage } from 'element-plus'

const router = useRouter()
const useUser = useUserStore()
const loginFormRef = ref(null)
const loginForm = ref({
  username: '',
  password: '',
})
const rules = ref({
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' },
  ],
})

const login = async () => {
  loginFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await Api.login(loginForm.value)
        if (response.data.status === 200) {
          console.log('登录成功，返回的 token:', response.data.token)
          ElMessage.success('登录成功')
          useUser.setToken(response.data.token) // 存储 Token
          useUser.setUser(response.data.user) // 存储用户信息
          router.push('/profile') // 跳转到个人中心页面
        } else {
          if (response.data.message && response.data.message.includes('用户不存在')) {
            ElMessage.error('账号不存在，请检查后重试')
          } else if (response.data.message && response.data.message.includes('密码错误')) {
            ElMessage.error('密码错误，请重新输入')
          } else {
            ElMessage.error(response.data.message || '登录失败')
          }
        }
      } catch (error) {
        if (error.response && error.response.data && error.response.data.message) {
          const msg = error.response.data.message
          if (msg.includes('用户不存在')) {
            ElMessage.error('账号不存在，请检查后重试')
          } else if (msg.includes('密码错误')) {
            ElMessage.error('密码错误，请重新输入')
          } else {
            ElMessage.error(msg)
          }
        } else {
          ElMessage.error('登录失败，请稍后重试')
        }
      }
    }
  })
}
</script>

<style scoped>
.loginView {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100vw;
  height: 100vh;
  background-color: #f5f5f5;
}

.login {
  width: 400px;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.login-button {
  width: 100%;
}

.register-link {
  margin-top: 10px;
  font-size: 14px;
  color: #666;
}

.register-link a {
  color: #409eff;
  text-decoration: none;
}

.register-link a:hover {
  text-decoration: underline;
}
</style>
